package com.can.controller;

import com.can.convert.UserConvert;
import com.can.domain.ResponseResult;
import com.can.domain.entity.LoginUser;
import com.can.domain.entity.Menu;
import com.can.domain.entity.User;
import com.can.domain.vo.AdminUserInfoVO;
import com.can.domain.vo.RoutersVO;
import com.can.domain.vo.UserInfoVO;
import com.can.enums.AppHttpCodeEnum;
import com.can.exception.SystemException;
import com.can.service.AdminLoginService;
import com.can.service.MenuService;
import com.can.service.RoleService;
import com.can.util.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class AdminLoginController {
    @Autowired
    private AdminLoginService adminloginService;
    @Autowired
    private MenuService menuService;
    @Autowired
    private RoleService roleService;

    @PostMapping("/user/login")
    public ResponseResult login(@RequestBody User user){
        if(!StringUtils.hasText(user.getUserName())){
            //提示 必须要传用户名
            throw new SystemException(AppHttpCodeEnum.REQUIRE_USERNAME);
        }
        return adminloginService.login(user);
    }

    @GetMapping("getInfo")
    public ResponseResult<AdminUserInfoVO> getInfo(){
        //获取当前登录的用户
        LoginUser loginUser = SecurityUtils.getLoginUser();
        //根据用户id查询权限信息
        List<String> perms = menuService.selectPermsByUserId(loginUser.getUser().getId());
        //根据用户id查询角色信息
        List<String> roleKeyList = roleService.selectRoleKeyByUserId(loginUser.getUser().getId());

        //获取用户信息
        User user = loginUser.getUser();
        UserInfoVO userInfoVO = UserConvert.INSTANCE.convert(user);

        //封装数据返回
        AdminUserInfoVO adminUserInfoVO = new AdminUserInfoVO(perms,roleKeyList,userInfoVO);
        return ResponseResult.okResult(adminUserInfoVO);
    }

    @GetMapping("getRouters")
    public ResponseResult<RoutersVO> getRouters(){
        Long userId = SecurityUtils.getUserId();
        //查询menu 结果是tree的形式
        List<Menu> menus = menuService.selectRouterMenuTreeByUserId(userId);
        //封装数据返回
        return ResponseResult.okResult(new RoutersVO(menus));
    }

    @PostMapping("/user/logout")
    public ResponseResult logout(){
        return adminloginService.logout();
    }

}